package com.jinyi.wwdeng.autodialer.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.jinyi.wwdeng.autodialer.MyApplication
import com.jinyi.wwdeng.autodialer.R
import com.jinyi.wwdeng.autodialer.data.CallTask
import com.jinyi.wwdeng.autodialer.databinding.ActivityMainBinding
import com.jinyi.wwdeng.autodialer.repository.CallTaskRepository
import com.jinyi.wwdeng.autodialer.ui.adapter.CallRecordAdapter
import com.jinyi.wwdeng.autodialer.utils.AppConfig
import com.jinyi.wwdeng.autodialer.utils.CallRecorderUtil
import com.jinyi.wwdeng.autodialer.utils.PermissionsUtil
import com.jinyi.wwdeng.autodialer.utils.ServiceUtil
import com.jinyi.wwdeng.autodialer.utils.TitleBarUtil
import com.jinyi.wwdeng.autodialer.utils.WavPlayer
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.ACTION_UPDATE_DIAL
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.ACTION_UPDATE_LOG
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.ACTION_UPDATE_REPORT
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.ACTION_UPDATE_SERVICE
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.ACTION_UPDATE_TOAST
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.ACTION_UPDATE_UPLOAD
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.EXTRA_MESSAGE
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.EXTRA_STATUS
import com.jinyi.wwdeng.autodialer.utils.event.EventSubscriber
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


/**
 * Git Bash zip 命令：
 * 在ADModule目录下：zip -r ADModule.zip .
 */
class MainActV2: BaseAct(), EventSubscriber {
    private var binding: ActivityMainBinding? = null
    val REQUEST_PERMISSIONS = 1001

    //数据管理
    private lateinit var repository: CallTaskRepository

    //号码列表
    private var callRecordAdapter: CallRecordAdapter? = null

    /**
     * 通知事件监听，用于Service更新UI
     */
    override fun publishEvent(intent: Intent) {
        Log.e("TAG",">>>>>>>>>>>>>>收到通知：${intent.action}")
        when(intent.action){
            ACTION_UPDATE_SERVICE -> {//更新服务状态
                val status = intent.getStringExtra(EXTRA_STATUS)
                binding?.let { binding ->
                    binding.btnStartService.isEnabled = status != "start"
                    binding.btnStopService.isEnabled = status != "stop"
                    binding.tvService.text = "服务状态: ${if (status == "start") "运行中" else "已停止"}"
                }
            }
            ACTION_UPDATE_DIAL -> {//更新通话状态
                val status = intent.getStringExtra(EXTRA_STATUS)
                binding?.let { binding ->
                    binding.tvDial.text = "通话状态: $status"
                }
            }
            ACTION_UPDATE_UPLOAD -> {//更新上传状态
                val status = intent.getStringExtra(EXTRA_STATUS)
                binding?.let { binding ->
                    binding.tvUpload.text = "上传状态: $status"
                }
            }
            ACTION_UPDATE_REPORT -> {//更新数据上报状态
                val status = intent.getStringExtra(EXTRA_STATUS)
                binding?.let { binding ->
                    binding.tvReport.text = "上报状态: $status"
                }
            }
            ACTION_UPDATE_LOG -> {//更新日志

            }
            ACTION_UPDATE_TOAST -> {
                val msg = intent.getStringExtra(EXTRA_MESSAGE)
                showToast(msg)
            }
        }
        updateLogList()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding?.root)
        TitleBarUtil.setStatusBarColor(this,"#FFFFFFFF".toColorInt())
        TitleBarUtil.setStatusBarLightMode(this,true)
        MyApplication.instance.publisher.register(this)

        initDefaultView()
        initComponents()
        initListeners()
    }

    override fun onResume() {
        super.onResume()
        updateLogList()
    }

    @SuppressLint("SetTextI18n")
    private fun initDefaultView(){
        binding?.let { binding ->
            binding.mainParentLayout.setPadding(32, TitleBarUtil.getStatusBarHeight() + 16,32,0)
            binding.txtUserName.text = AppConfig.userName.ifEmpty { getString(R.string.app_name) }

            binding.btnStartService.isEnabled = true
            binding.btnStopService.isEnabled = true
            binding.tvService.text = "服务状态: 未启动"

            binding.tvDial.text = "通话状态: 空闲中"
            binding.tvUpload.text = "上传状态: 空闲中"
            binding.tvReport.text = "上报状态: 空闲中"
        }
    }

    private fun initComponents() {
        if (!checkAndRequestPermissions()) {
            return
        }
        repository = CallTaskRepository.getInstance(this)
    }

    private fun initListeners() {
        //启动拨号服务
        binding?.btnStartService?.setOnClickListener {
            if (checkAndRequestPermissions()) {
                startDialerService()
            }
        }
        //停止拨号服务
        binding?.btnStopService?.setOnClickListener {
            stopDialerService()
        }
        binding?.btnClear?.setOnClickListener {
            clearAllData()
        }
    }

    /**
     * 检查权限
     */
    private fun checkAndRequestPermissions(): Boolean {
        val missingPermissions = mutableListOf<String>()

        if (!PermissionsUtil.hasCallPermission(this)) {
            missingPermissions.add(Manifest.permission.CALL_PHONE)
        }

        if (!PermissionsUtil.hasPhoneStatePermission(this)) {
            missingPermissions.add(Manifest.permission.READ_PHONE_STATE)
        }

        if (!PermissionsUtil.hasRecordAudioPermission(this)) {
            missingPermissions.add(Manifest.permission.RECORD_AUDIO)
        }

        if (!PermissionsUtil.hasAudioOutputPermission(this)){
            missingPermissions.add(Manifest.permission.CAPTURE_AUDIO_OUTPUT)
        }

        if (!PermissionsUtil.hasIncallExperiencePermission(this)){
            missingPermissions.add("android.permission.CONTROL_INCALL_EXPERIENCE")
        }

        return if (missingPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, missingPermissions.toTypedArray(), REQUEST_PERMISSIONS)
            false
        } else {
            true
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSIONS) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (allGranted) {
                initComponents()
                Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "需要权限才能运行自动拨号", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 启动拨号服务
     */
    private fun startDialerService() {
        val success = ServiceUtil.startAutoCallService(this)
        if (success) {
//            showToast("服务启动请求已发送")
        } else {
//            showToast("服务正在运行中")
        }
        updateLogList()
    }

    /**
     * 停止拨号服务
     */
    private fun stopDialerService() {
        val success = ServiceUtil.stopAutoCallService(this)
        if (success) {
//            showToast("服务已停止")
        } else {
//            showToast("服务停止失败")
        }
        updateLogList()
    }

    /**
     * 清空数据
     */
    private fun clearAllData() {
        AlertDialog.Builder(this)
            .setTitle("确认清空")
            .setMessage("确定要清空所有号码数据吗？")
            .setPositiveButton("确定") { dialog, which ->
                try {
                    lifecycleScope.launch {
                        repository.deleteAllTasks()
                        delay(500)
                        Toast.makeText(this@MainActV2, "数据已清空", Toast.LENGTH_SHORT).show()
                        updateLogList()
                    }
                } catch (e: Exception) {
                    Toast.makeText(this@MainActV2, "清空数据失败", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 更新日志列表
     */
    private fun updateLogList() {
        lifecycleScope.launch {
            try {
                val allTaskList = repository.getAllTasks()
                //刷新号码列表
                updateNumberList(allTaskList)
            } catch (e: Exception) {
                Log.e("MainActivity", "更新UI失败: ${e.message}")
            }
        }
    }

    /**
     * 更新号码列表
     */
    @SuppressLint("SetTextI18n")
    private fun updateNumberList(numberList: List<CallTask>){
        if (callRecordAdapter == null){
            binding?.let { binding ->
                binding.recyclerView.setHasFixedSize(true)
                binding.recyclerView.isNestedScrollingEnabled = false
                binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
                val layoutManager = LinearLayoutManager(this)
                binding.recyclerView.layoutManager = layoutManager
            }
            callRecordAdapter = CallRecordAdapter(numberList.toMutableList(), onClickPlay = {view , _, model ->
                when(view.id){
                    R.id.tvInfo -> {
                        //拨号
                        Log.e("TAG","拨号>>>>>>>>>>>>>${model.phoneNumber}")
//                        lifecycleScope.launch {
//                            startCallAction(model)
//                        }
                    }
//                    R.id.tvInfo -> {
//                        Log.e("TAG","播放录音>>>>>>>>>>>>>${model.phoneNumber},${model.audioPath}")
//                        val wavFile = File(model.audioPath)
//                        WavPlayer.play(this, wavFile) {
//                            Log.d("Test", "播放完成")
//                        }
//                    }
                }
            })
            binding?.recyclerView?.adapter = callRecordAdapter
            return
        }
        callRecordAdapter?.updateData(numberList.toMutableList())
    }

    override fun onDestroy() {
        super.onDestroy()
        MyApplication.instance.publisher.detach(this)
        CallRecorderUtil.release()
        WavPlayer.stop()
        stopDialerService()
    }
}